package com.share.jdbc.rule;

import com.share.common.utils.DataSourceUtils;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public final class RawJdbcJavaShardingTableOnlyMain {
    
    // CHECKSTYLE:OFF
    public static void main(final String[] args) throws SQLException {
    // CHECKSTYLE:ON
//        new ShardingJdbc(getShardingDataSource()).demo();
    }
    
   private static DataSource getShardingDataSource() throws SQLException {
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
        shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
        shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item");
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties());
    }

    /**
     * order 分表规则
     * @return
     */
    private static TableRuleConfiguration getOrderTableRuleConfiguration() {
        TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order");

//        orderTableRuleConfig.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("user_id", "dbShardingAlgorithm"));
//        orderTableRuleConfig.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("", ""));
        orderTableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLOWER", "123"));
        return orderTableRuleConfig;
    }
    
    private static TableRuleConfiguration getOrderItemTableRuleConfiguration() {
//        TableRuleConfiguration orderItemTableRuleConfig = new TableRuleConfiguration();
//        orderItemTableRuleConfig.setLogicTable("t_order_item");
//        orderItemTableRuleConfig.setActualDataNodes("demo_ds_0.t_order_item_${[0, 1]}");
//        return orderItemTableRuleConfig;
        return null;
    }

    /**
     * 创建数据源
     * @return
     */
    private static Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>(1, 1);
        result.put("demo_ds_0", DataSourceUtils.createDataSource("demo_ds_0"));
        result.put("demo_ds_1", DataSourceUtils.createDataSource("demo_ds_1"));
        return result;
    }
}
